import SwiftUI

struct PersonBill: Identifiable {
    let id = UUID()
    let name: String
    let items: [ExpenseItem]
    let total: Double
}

struct ReceiptDetailsView: View {
    let receipt: ExpenseAIResponse

    @State private var items: [ExpenseItem] = []
    @State private var peopleSelections: [PersonSelection] = []
    @State private var numberOfPeople = 1
    @State private var showSummary = false
    @State private var perPersonResults: [PersonBill] = []
    @State private var splitEvenly = false


    var body: some View {
        ScrollView {
            VStack(spacing: 24) {

                Text(receipt.merchant ?? "Unknown Merchant")
                    .font(.largeTitle).bold()

                VStack(alignment: .leading, spacing: 6) {
                    Text("Subtotal: \(receipt.subtotal ?? 0)")
                    Text("Tax: \(receipt.tax ?? 0)")
                    Text("Tip: \(receipt.tip ?? 0)")
                    Text("Discount: \(receipt.discount ?? 0)")
                    Text("Total: \(receipt.total ?? 0)").bold()
                }

                Divider()

                HStack {
                    Text("Number of people: \(numberOfPeople)")
                        .font(.headline)

                    Spacer()

                    Button {
                        removePerson()
                    } label: {
                        Image(systemName: "minus.circle")
                    }
                    .disabled(numberOfPeople == 1)

                    Button {
                        addPerson()
                    } label: {
                        Image(systemName: "plus.circle")
                    }
                }

                Divider()

                Toggle("Split total evenly", isOn: $splitEvenly)
                    .toggleStyle(.switch)
                    .padding(.vertical)

                if splitEvenly == false {
                    if items.isEmpty {
                        Text("No items found.")
                    } else {
                        ForEach($peopleSelections) { $person in
                            personSection(person: $person)
                        }
                    }
                } else {
                    Text("Each person will pay an equal share.")
                        .foregroundColor(.gray)
                        .padding(.bottom)
                }


                Button("Continue") {
                    finalizeSplit()
                }
                .frame(maxWidth: .infinity)
                .padding()
                .background(.blue)
                .foregroundColor(.white)
                .cornerRadius(12)
            }
            .padding()
        }
        .sheet(isPresented: $showSummary) {
            SplitSummaryView(results: perPersonResults)
        }
        .onAppear {
            setup()
        }
    }
}

extension ReceiptDetailsView {
    var receiptSummarySection: some View {
        VStack(alignment: .leading, spacing: 6) {
            Text("Subtotal: $\(receipt.subtotal ?? 0, specifier: "%.2f")")
            Text("Tax: $\(receipt.tax ?? 0, specifier: "%.2f")")
            Text("Tip: $\(receipt.tip ?? 0, specifier: "%.2f")")
            Text("Discount: $\(receipt.discount ?? 0, specifier: "%.2f")")
            Text("Total: $\(receipt.total ?? 0, specifier: "%.2f")")
                .font(.headline)
        }
    }
}


extension ReceiptDetailsView {
    func setup() {
        items = (receipt.items ?? []).map {
            ExpenseItem(name: $0.name ?? "Unknown", amount: $0.amount ?? 0)
        }

        let defaults = Dictionary(uniqueKeysWithValues: items.map { ($0.id, false) })

        peopleSelections = [
            PersonSelection(name: "Person 1", itemSelections: defaults)
        ]
    }
}

struct SplitSummaryView: View {
    let results: [PersonBill]

    var body: some View {
        NavigationView {
            List {
                ForEach(results) { result in
                    Section(header: Text(result.name)) {
                        ForEach(result.items) { item in
                            HStack {
                                Text(item.name)
                                Spacer()
                                Text("$\(item.amount, specifier: "%.2f")")
                            }
                        }

                        HStack {
                            Text("Total").bold()
                            Spacer()
                            Text("$\(result.total, specifier: "%.2f")").bold()
                        }
                    }
                }
            }
            .navigationTitle("Split Summary")
        }
    }
}

extension ReceiptDetailsView {
    func finalizeSplit() {
        if splitEvenly {
            finalizeEvenSplit()
            return
        }
        var results: [PersonBill] = []

        for person in peopleSelections {
            let selectedItems = items.filter { person.itemSelections[$0.id] == true }
            let total = selectedItems.reduce(0) { $0 + $1.amount }

            results.append(
                PersonBill(name: person.name, items: selectedItems, total: total)
            )
        }

        perPersonResults = results
        showSummary = true
    }
    
    func finalizeEvenSplit() {
        
        let subtotal = receipt.subtotal ?? 0
        let tax = receipt.tax ?? 0
        let tip = receipt.tip ?? 0
        let discount = receipt.discount ?? 0

        
        let computedTotal = subtotal + tax + tip - discount
        let total = receipt.total ?? computedTotal

        let share = total / Double(numberOfPeople)

        var results: [PersonBill] = []
        for i in 1...numberOfPeople {
            results.append(
                PersonBill(
                    name: "Person \(i)",
                    items: [],
                    total: share
                )
            )
        }

        perPersonResults = results
        showSummary = true
    }


}

extension ReceiptDetailsView {
    @ViewBuilder
    func personSection(person: Binding<PersonSelection>) -> some View {
        VStack(alignment: .leading, spacing: 12) {

            Text(person.wrappedValue.name)
                .font(.title3)
                .bold()

            ForEach(items) { item in
                HStack {
                    VStack(alignment: .leading) {
                        Text(item.name)
                        Text("$\(item.amount, specifier: "%.2f")")
                            .foregroundColor(.gray)
                    }

                    Spacer()

                    Toggle("", isOn: Binding(
                        get: { person.itemSelections.wrappedValue[item.id] ?? false },
                        set: { person.itemSelections.wrappedValue[item.id] = $0 }
                    ))

                    .labelsHidden()
                }
            }
        }
        .padding()
        .background(Color(.secondarySystemBackground))
        .cornerRadius(12)
    }
}

extension ReceiptDetailsView {
    func addPerson() {
        numberOfPeople += 1
        let defaults = Dictionary(uniqueKeysWithValues: items.map { ($0.id, false) })

        peopleSelections.append(
            PersonSelection(name: "Person \(numberOfPeople)", itemSelections: defaults)
        )
    }

    func removePerson() {
        guard numberOfPeople > 1 else { return }
        numberOfPeople -= 1
        peopleSelections.removeLast()
    }
}


extension ReceiptDetailsView {

    var peopleCountSection: some View {
        HStack {
            Text("Number of people: \(numberOfPeople)")
                .font(.headline)

            Spacer()

            Button(action: decreasePerson) {
                Image(systemName: "minus.circle")
                    .font(.title2)
            }
            .disabled(numberOfPeople == 1)

            Button(action: increasePerson) {
                Image(systemName: "plus.circle")
                    .font(.title2)
            }
        }
        .padding(.horizontal)
    }

    func increasePerson() {
        numberOfPeople += 1
        let defaults = Dictionary(uniqueKeysWithValues: items.map { ($0.id, false) })

        peopleSelections.append(
            PersonSelection(name: "Person \(numberOfPeople)", itemSelections: defaults)
        )
    }

    func decreasePerson() {
        guard numberOfPeople > 1 else { return }
        numberOfPeople -= 1
        peopleSelections.removeLast()
    }
}
